/*
 * @depends component.js, Window.js
 */
QFinance.component.TransactionEditWindow = Ext.extend( QFinance.ui.Window, {
    // Configuration
    isNew: true,
    canChangeDate: true,
    canChangeDescription: true,
    canChangeAmount: true,
    canChangeSourceAccount: true,
    canChangeDestinationAccount: true,
    canChangeCategory: true,
    accountEditMode: 'both',
    contextAccountID: null,	
    autoLoadRecord: true,
    record: null,
    requireCategory: true,
	
    // Localization
    saveText: 'Save',
    closeText: 'Close',
    idText: 'ID',
    dateText: 'Date',
    accountEmptyText: 'Select a account',
    sourceAccountText: 'Source account',
    destinationAccountText: 'Destination account',
    descriptionText: 'Description',
    bankMemoText: 'Bank memo',
    amountText: 'Amount',
    defaultTitleText: 'Edit transaction',
    editingTitleText: 'Editing transaction: {0}',
    pleaseSelectAnCategory: 'Please, select an category.',
    fillRequiredFields: 'Please, fill required fields.',
    removeTransactionTitleText: 'Drag and drop',
    removeTransactionText: 'Remove annotated transaction?',
    formValidationTitleText: 'Form validation',
    reloadDataText: 'Reload data',
    categoryText: 'Category',
    markText: 'Mark',
    markEmptyText: 'Select an mark',
			
    // Components
    accountStore: null,
    markStore: null,
    formPanel: null,
    categoryPanel: null,
    sourceComboBox: null,
    destinationComboBox: null,
    markComboBox: null,
    dropTarget: null,
	
    constructor: function(config) {
        Ext.apply(this,config);
		
        this.accountStore = new Ext.data.DirectStore({
            storeId: 'account-store',
            directFn: QFinance.Remoting.AccountAction.getAccountsMinus,
            paramsAsHash: false,
            idProperty: 'id',
            root: 'data',
            successProperty: 'success',
            paramOrder: [ 'excludeAccount' ],
            baseParams: {
                excludeAccount: this.contextAccountID
            },
            fields: [
            {
                name: 'id',
                type: 'int'
            },
            {
                name: 'accountName'	    		    
            },
            {
                name: 'accountType'
            }
            ],
            listeners: {
                scope: this,
                beforeload: function(store, options) {
                    var components = [];
                    if (this.sourceComboBox)
                        components.push(this.sourceComboBox);
                    if (this.destinationComboBox)
                        components.push(this.destinationComboBox);
                    store.id = this.getProcessStatusManager().start(components);
                    delete components;
                },				
                load: function(store, records, options) {
                    this.getProcessStatusManager().success(store.id);
                },			
                exception: function(dataProxy, type, action, options, response, arg ) {
                    var message = '';
                    var where = '';
                    if (response.result) {
                        message = response.result.message;
                        if (response.result.type == 'exception')
                            where = response.result.where;
                    } else {
                        message = response.message;
                    }
                    this.getProcessStatusManager().error(this.accountStore.id, message);                    
                    QFinance.service.DeveloperService.log('Store failure: ' + message + ' where\n' + where);
                }
            }		
        });

        this.markStore = new Ext.data.DirectStore({
            storeId: 'mark-store',
            directFn: QFinance.Remoting.TransactionEditWindowAction.getMarks,
            paramsAsHash: false,
            idProperty: 'id',
            root: 'data',
            successProperty: 'success',
            fields: [{
                name: 'id',
                type: 'int'
            },{
                name: 'name'	    		    
            }],
            listeners: {
                scope: this,
                beforeload: function(store, options) {
                    store.id = this.getProcessStatusManager().start([this.markComboBox]);
                },				
                load: function(store, records, options) {
                    this.getProcessStatusManager().success(store.id);
                },			
                exception: function(dataProxy, type, action, options, response, arg ) {
                    var message = '';
                    var where = '';
                    if (response.result) {
                        message = response.result.message;
                        if (response.result.type == 'exception')
                            where = response.result.where;
                    } else {
                        message = response.message;
                    }
                    this.getProcessStatusManager().error(this.markStore.id, message);                    
                    QFinance.service.DeveloperService.log('Store failure: ' + message + ' where\n' + where);
                }
            }		
        });
		
        this.addEvents(['save']);
		
        Ext.applyIf(this, {
            width: 400,
            height: 500
        });
		
        QFinance.component.TransactionEditWindow.superclass.constructor.call(this);
    },
	
    show: function() {		
        this.dropTarget = this.body;
        var me = this;
		
        var formPanelDropTarget = new Ext.dd.DropTarget(this.dropTarget, {
            ddGroup     : 'gridDDGroup',
            notifyDrop  : function(ddSource, e, data){
                var selectedRecord = ddSource.dragData.selections[0];
                var idField = me.formPanel.getForm().findField('id');
                var backupID = 0;				
				
                var removeTransactions = new QFinance.ui.MessageBox();
                removeTransactions.show({
                    title: me.removeTransactionTitleText,
                    msg: me.removeTransactionText,
                    buttons: Ext.Msg.YESNOCANCEL,				   
                    fn: function(btn, text, opt) {
                        if (btn == 'yes')
                            ddSource.grid.store.remove(selectedRecord);
                        else if (btn == 'cancel')
                            return (false);
					   
                        if (idField) {
                            backupID = idField.getValue();
                        }
						 
                        me.formPanel.getForm().loadRecord(selectedRecord);
						
                        if (idField) {
                            idField.setValue(backupID);
                        }
                        
                        return true;
                    },
                    renderTo: me.body,
                    animEl: 'elId',
                    icon: Ext.MessageBox.QUESTION
                });

                return(true);
            }
        }, this);
        QFinance.component.TransactionEditWindow.superclass.show.call(this);
						
        var dataLoadID = this.getProcessStatusManager().start([this]) 
        this.accountStore.load({
            scope: this,
            callback: function() {
                this.markStore.load({
                    scope: this,
                    callback: function() {
                        if (this.autoLoadRecord && this.record) {
                            this.loadRecord();
                        }                        
                        this.getProcessStatusManager().success(dataLoadID);
                    }
                })
            }
        });	
    },

    initComponent: function() {		
        var formPanelConfig = this.getFormPanelConfig();
        this.formPanel = new Ext.form.FormPanel(formPanelConfig);
						
        Ext.apply(this,{
            title: this.defaultTitleText,
            layout: 'vbox',
            bodyStyle:'padding: 5px',
            layoutConfig: {
                align : 'stretch',
                pack  : 'start'
            },	
            items: [ this.formPanel, {
                xtype: 'fieldset',
                title: this.categoryText,
                layout: 'fit',
                flex: 1,
                items: [ this.categoryPanel = new QFinance.component.CategoriesEditPanel({
                    disabled: !this.canChangeCategory,
                    autoSelectCategoryID: (this.record && this.record.get('categoryID') > 0) ? this.record.get('categoryID') : 'root',
                    ownerWindow: this
                })]
            }],
            tbar: [{
                text: this.reloadDataText,
                iconCls: 'fugue-arrow-circle',
                scope: this,
                handler: this.doRefreshData
            }]
        });		
		
        QFinance.component.TransactionEditWindow.superclass.initComponent.call(this);
    },
    
    initStatusBar: function(toolbar) {
        toolbar.add(new Ext.Button({
            text: this.saveText,
            iconCls: 'fugue-disk-black',
            scope: this,
            handler: function() {
                if (this.checkValid()) {
                    this.doSave();
                    this.close();
                }
            }
        }));
        
        toolbar.add(new Ext.Button({
            text: this.closeText,
            iconCls: 'fugue-door-open-out',				
            scope: this,
            handler: function() {
                this.close();
            }
        }));
    },
	
    getFormPanelConfig: function() {
        var formPanelConfig = {			
            defaultType: 'textfield',				
            autoHeight: true,
            frame: true,
            labelWidth: 120,
            defaults: {
                anchor: '100%'
            },
            items: this.getFormPanelItems()					
        };
		
        return formPanelConfig;
    },
	
    getFormPanelItems: function() {
        var formPanelItemsConfig = [];
		
        formPanelItemsConfig.push({
            fieldLabel: this.idText,
            name: 'id',
            readOnly: true
        });		
		
        formPanelItemsConfig.push({
            xtype: 'datefield',
            fieldLabel: this.dateText,
            name: 'date',
            format: QFinance.dateFormat,
            readOnly: !this.canChangeDate
        });
		
        if (this.accountEditMode == QFinance.component.TransactionEditWindow.editModes.BOTH || this.accountEditMode == QFinance.component.TransactionEditWindow.editModes.SOURCE) {
            formPanelItemsConfig.push(this.sourceComboBox = new Ext.form.ComboBox({
                fieldLabel: this.sourceAccountText,
                name: 'sourceAccountID',
                store: this.accountStore,
                typeAhead: true,
                triggerAction: 'all',
                emptyText: this.accountEmptyText,
                selectOnFocus: true,
                valueField: 'id',
                displayField: 'accountName',
                mode: 'local',
                forceSelection: true,
                value: null,
                readOnly: !this.canChangeSourceAccount
            }));
        }
		
        if (this.accountEditMode == QFinance.component.TransactionEditWindow.editModes.BOTH || this.accountEditMode == QFinance.component.TransactionEditWindow.editModes.DESTINATION) {
            formPanelItemsConfig.push(this.destinationComboBox = new Ext.form.ComboBox({
                fieldLabel: this.destinationAccountText,
                name: 'destinationAccountID',
                store: this.accountStore,
                typeAhead: true,
                triggerAction: 'all',
                emptyText: this.accountEmptyText,
                selectOnFocus: true,
                valueField: 'id',
                displayField: 'accountName',
                mode: 'local',
                forceSelection: true,
                value: null,
                readyOnly: !this.canChangeDestinationAccount
            }));
        } 

        formPanelItemsConfig.push( this.markComboBox = new Ext.form.ComboBox({            
            fieldLabel: this.markText,
            name: 'markID',
            store: this.markStore,
            typeAhead: true,
            triggerAction: 'all',
            emptyText: this.markEmptyText,
            selectOnFocus: true,
            valueField: 'id',
            displayField: 'name',
            mode: 'local',
            forceSelection: true,
            allowBlank: true,
            value: null
        }));
	
        formPanelItemsConfig.push({
            fieldLabel: this.descriptionText,
            name: 'description',
            readOnly: !this.canChangeDescription
        });
		
        formPanelItemsConfig.push({
            fieldLabel: this.bankMemoText,
            name: 'bankMemo',
            readOnly: true
        });
		
        formPanelItemsConfig.push({
            xtype: 'numberfield',
            fieldLabel: this.amountText,
            name: 'amount',
            readOnly: !this.canChangeAmount ,
            allowBlank: false,
            decimalSeparator: QFinance.decimalSeparator
        });
		
        return formPanelItemsConfig; 
    },    
        
    doRefreshData: function() {
        this.accountStore.load();
        this.markStore.load();
    },
	
    loadRecord: function() {
        var loadRecordID = this.getProcessStatusManager().start([this.formPanel]);
        if (!this.isNew)
            this.setTitle(String.format(this.editingTitleText,this.record.get('description') ? this.record.get('description') : this.record.get('bankMemo'))); 
        this.formPanel.getForm().loadRecord( this.record );
        this.getProcessStatusManager().success(loadRecordID);
    },
	
    checkValid: function() {
        var valid = true;
        var alertMessage
		
        if (!this.formPanel.getForm().isValid()) {
            valid = false;
            alertMessage = new QFinance.ui.MessageBox();
            alertMessage.show({
                title: this.formValidationTitleText,
                msg: this.fillRequiredFields,
                icon: alertMessage.WARNING,
                buttons: alertMessage.OK,
                renderTo: this.body
            });
        } else {
            if (this.requireCategory) {
                var selectedCategory = this.categoryPanel.getSelectedCategory();
                if (!selectedCategory) {
                    valid = false;
                    alertMessage = new QFinance.ui.MessageBox();
                    alertMessage.show({
                        title: this.formValidationTitleText,
                        msg: this.pleaseSelectAnCategory,
                        icon: alertMessage.WARNING,
                        buttons: alertMessage.OK,
                        renderTo: this.body
                    });
                }
            }
        }
		
        return valid;
    },
	
    doSave: function() {
        var selectedRecord;
        
        this.formPanel.getForm().updateRecord(this.record);		
        this.record.beginEdit();
		
        if (this.accountEditMode == QFinance.component.TransactionEditWindow.editModes.SOURCE || this.accountEditMode == QFinance.component.TransactionEditWindow.editModes.BOTH) {
            selectedRecord = this.accountStore.getById( this.sourceComboBox.getValue() );
            if (selectedRecord) {			
                this.record.set('sourceAccountName', selectedRecord.get('accountName'));
            } else {
                this.record.set('sourceAccountName', null);
            }
        } 
        if (this.accountEditMode == QFinance.component.TransactionEditWindow.editModes.DESTINATION || this.accountEditMode == QFinance.component.TransactionEditWindow.editModes.BOTH) {
            selectedRecord = this.accountStore.getById( this.destinationComboBox.getValue() );
            if (selectedRecord) {
                this.record.set('destinationAccountName', selectedRecord.get('accountName') );	
            } else {
                this.record.set('destinationAccountName', null );
            }
        } 
        
        selectedRecord = this.markStore.getById( this.markComboBox.getValue() );
        if (selectedRecord) {
            this.record.set('markName', selectedRecord.get('name') );	
        } else {
            this.record.set('markName', null );	
        }
		
        if (this.canChangeCategory) {
            var selectedCategory = this.categoryPanel.getSelectedCategory();
            if (selectedCategory) {
                this.record.set('categoryID', selectedCategory.get('id'));
                this.record.set('categoryName', selectedCategory.get('categoryName'));
            }
        }
		
        this.record.endEdit();		
		
        this.fireEvent('save', this.record);
    }	
});

QFinance.component.TransactionEditWindow.editModes = {
    SOURCE: 'source',
    DESTINATION: 'destination',
    BOTH: 'both'
};

Ext.reg('QFinance.component.TransactionEditWindow', QFinance.component.TransactionEditWindow);